package com.base.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;

import java.util.Collections;
import java.util.List;

public abstract class BaseListAdapter<T, VH extends BaseListAdapter.ViewHolder> extends BaseAdapter {
    private List<T> arrayList;
    private final Context mContext;

    public BaseListAdapter(Context context) {
        mContext = context;
    }

    public BaseListAdapter(Context context, List<T> arrList) {
        this.mContext = context;
        changedList(arrList);
    }

    public void notifyList() {
        notifyList(null);
    }

    public void notifyList(List<T> arrList) {
        changedList(arrList);
        notifyDataSetChanged();
    }

    @NonNull
    public List<T> getList() {
        return null == arrayList ? Collections.emptyList() : arrayList;
    }

    public void changedList(List<T> arrList) {
        if (null == arrList)
            this.arrayList = Collections.emptyList();
        else
            this.arrayList = arrList;
    }

    public Context getContext() {
        return mContext;
    }

    @Override
    public int getCount() {
        return arrayList == null ? 0 : arrayList.size();
    }

    @Override
    public T getItem(int position) {
        return arrayList == null ? null : arrayList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    public abstract @LayoutRes
    int adapterLayout();

    public View getConvertView(ViewGroup parent) {
        LayoutInflater inflater = LayoutInflater.from(mContext);
        return inflater.inflate(adapterLayout(), parent, false);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        VH holder;
        if (convertView == null) {
            convertView = getConvertView(parent);
            holder = createViewHolder(convertView);
            convertView.setTag(holder);
        } else //noinspection unchecked
            holder = (VH) convertView.getTag();
        onViewHolder(holder, position);
        return convertView;
    }

    public abstract VH createViewHolder(View view);

    public abstract void onViewHolder(@NonNull VH holder, int position);

    public static abstract class ViewHolder {
        private final View view;

        public ViewHolder(@NonNull View view) {
            this.view = view;
            bindViews(view);
        }

        public View getView() {
            return view;
        }

        public abstract void bindViews(@NonNull View view);
    }
}
